package com.hiray.widget

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.TypedArray
import android.support.annotation.StringRes
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import android.view.Gravity

import com.hiray.R

import android.view.ViewGroup.LayoutParams.WRAP_CONTENT

class CenterTitleToolBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.toolbarStyle) : Toolbar(context, attrs, defStyleAttr) {
    private var titleTextView: AppCompatTextView? = null

    init {
        initialize(context, attrs, defStyleAttr)

    }

    @SuppressLint("PrivateResource")
    private fun initialize(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        super.setTitle(null)
        val a = context.obtainStyledAttributes(attrs, R.styleable.Toolbar, defStyleAttr, 0)
        // same as ToolBar's default color
        val titleTextColor = a.getColor(R.styleable.Toolbar_titleTextColor, -0x1)
        //fetch the customized TextAppearance
        val appearance = a.getResourceId(R.styleable.Toolbar_titleTextAppearance, 0)
        val title = a.getString(R.styleable.Toolbar_title)
        a.recycle()
        titleTextView = AppCompatTextView(context)
        val layoutParams = Toolbar.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
        layoutParams.gravity = Gravity.CENTER
        titleTextView!!.layoutParams = layoutParams
        titleTextView!!.text = title
        titleTextView!!.setTextColor(titleTextColor)

        if (appearance != 0)
            titleTextView!!.setTextAppearance(context, appearance)
        else
            titleTextView!!.setTextAppearance(context, R.style.TextAppearance_AppCompat_Title)
        addView(titleTextView)
    }


    //override  setting text to our own textview
    override fun setTitle(title: CharSequence) {
        if (titleTextView != null) {
            titleTextView!!.text = title
        }
    }

    override fun setTitle(@StringRes resId: Int) {
        title = resources.getString(resId)
    }
}
